import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {Globals} from '../../../globals';
import {Charts} from '../../../../../_mock/charts';
import {Chart, registerShape} from '@antv/g2';
import {BaseService} from '../../../shared/service/base.service';
import {ApiUrl} from '../../../config/api-url';
import {parse} from 'ts-node';
import {UserInfoModel} from '../../../models/user-info.model';
import {RoleIdEnum} from '../../../enums/role-id.enum';
import {Consts} from '../../../config/consts';

@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ['./second.component.less']
})
export class SecondComponent implements OnInit, AfterViewInit {

  isMobile = Globals.isMobile();
  curIndex = 0;
  type = 'day';
  rankingList = [];
  userTurnoverTopList = [];
  userOrderCountTopList = [];
  merchantTurnoverTopList = [];
  merchantOrderCountTopList = [];
  agencyTotalCommissionTopList = [];
  chartWidth = 0;
  year: any;
  month: any;

// 用户信息
  userInfo: UserInfoModel;
  roleIdEnum = {
    SUPER_ADMINISTRATOR: RoleIdEnum.SUPER_ADMINISTRATOR,
    AGENT: RoleIdEnum.AGENT,
    MERCHANT: RoleIdEnum.MERCHANT,
    SUB_ACCOUNT: RoleIdEnum.SUB_ACCOUNT,
  };
  @ViewChild('daySales') daySales: ElementRef;
  @ViewChild('dayCount') dayCount: ElementRef;
  @ViewChild('dayProfit') dayProfit: ElementRef;
  @ViewChild('monthSales') monthSales: ElementRef;
  @ViewChild('monthCount') monthCount: ElementRef;
  @ViewChild('monthProfit') monthProfit: ElementRef;


  ngOnInit(): void {
    this.userInfo = JSON.parse(sessionStorage.getItem(Consts.USER_INFO));
    let date = new Date();
    this.year = date.getFullYear();
    this.month = date.getMonth() + 1;
  }

  constructor(private baseService: BaseService,) {

  }

  ngAfterViewInit() {
    if (this.userInfo.roleId == this.roleIdEnum.SUPER_ADMINISTRATOR || this.userInfo.roleId == this.roleIdEnum.AGENT){
      this.findAgencyTurnoverTop();
      this.findAgencyOrderCountTop();
      this.findAgencyTotalCommissionTop();
    }else if (this.userInfo.roleId == this.roleIdEnum.MERCHANT || this.userInfo.roleId == this.roleIdEnum.SUB_ACCOUNT){
      this.findMerchantTurnoverTop();
      this.findMerchantOrderCountTop();
    }
    if (this.type == 'month') {
      this.chartWidth = this.monthSales.nativeElement.clientWidth;
    } else {
      this.chartWidth = this.daySales.nativeElement.clientWidth;
    }
    this.selectSales();
    console.log('ngAfterViewInit.......');

  }


  /**
   * 统计运营商销售排行前几
   */
  findAgencyTurnoverTop() {
    let type = this.type == 'month' ? 2 : 1;
    this.baseService.get(ApiUrl.HomeUrl + '/findUserTurnoverTop?type=' + type).subscribe(res => {
      this.userTurnoverTopList = res.data;
    });
  }

  /**
   * 统计合作伙伴订单交易笔数排行前几
   */
  findAgencyOrderCountTop() {
    let type = this.type == 'month' ? 2 : 1;
    this.baseService.get(ApiUrl.HomeUrl + '/findUserOrderCountTop?type=' + type).subscribe(res => {
      this.userOrderCountTopList = res.data;
    });
  }

  /**
   * 统计合作伙伴利润排行前几
   */
  findAgencyTotalCommissionTop() {
    let type = this.type == 'month' ? 2 : 1;
    this.baseService.get(ApiUrl.HomeUrl + '/findAgencyTotalCommissionTop?type=' + type).subscribe(res => {
      this.agencyTotalCommissionTopList = res.data;
    });
  }

  /**
   * 统计门店销售排行前几
   */
  findMerchantTurnoverTop() {
    let type = this.type == 'month' ? 2 : 1;
    this.baseService.get(ApiUrl.HomeUrl + '/findMerchantTurnoverTop?type=' + type).subscribe(res => {
      this.merchantTurnoverTopList = res.data;
    });
  }

  /**
   * 统计门店订单交易笔数排行前几
   */
  findMerchantOrderCountTop() {
    let type = this.type == 'month' ? 2 : 1;
    this.baseService.get(ApiUrl.HomeUrl + '/findMerchantOrderCountTop?type=' + type).subscribe(res => {
      this.merchantOrderCountTopList = res.data;
    });
  }

  //获取当前tabCurIndex值
  curTabIndex(e) {
    this.curIndex = e;
    console.log('this.curIndex:' + this.curIndex);
  }

  selectCount() {
    // console.log(this.monthCount.nativeElement)
    if (this.type == 'month') {
      //未宣染生成图表的，才生成
      if (!this.monthCount.nativeElement.innerHTML) {
        this.monthCountChart(this.chartWidth);
        console.log('重新生成交易笔数月表');
      }
    } else {
      //未宣染生成图表的，才生成
      if (!this.dayCount.nativeElement.innerHTML) {
        this.dayCountChart(this.chartWidth);
        console.log('重新生成交易笔数日表');
      }

    }
  }

  selectProfit() {
    if (this.type == 'month') {
      //未宣染生成图表的，才生成
      if (!this.monthProfit.nativeElement.innerHTML) {
        this.monthProfitChart(this.chartWidth);
        console.log('重新生成利润月表');
      }
    } else {
      //未宣染生成图表的，才生成
      if (!this.dayProfit.nativeElement.innerHTML) {
        this.dayProfitChart(this.chartWidth);
        console.log('重新生成利润日表');
      }
    }
  }

  selectSales() {
    if (this.type == 'month') {
      //未宣染生成图表的，才生成
      if (!this.monthSales.nativeElement.innerHTML) {
        this.monthSalesChart(this.chartWidth);
        console.log('重新生成销量月表');
      }
    } else {
      //未宣染生成图表的，才生成
      if (!this.daySales.nativeElement.innerHTML) {
        this.daySalesChart(this.chartWidth);
        console.log('重新生成销量日表');
      }
    }
  }

  radioChange() {
    console.log('点击了按月，按天按钮');
    let date = new Date();
    this.year = date.getFullYear();
    this.month = date.getMonth() + 1;
    //重新查询
    if (this.userInfo.roleId == this.roleIdEnum.SUPER_ADMINISTRATOR || this.userInfo.roleId == this.roleIdEnum.AGENT){
      this.findAgencyTurnoverTop();
      this.findAgencyOrderCountTop();
      this.findAgencyTotalCommissionTop();
    }else if (this.userInfo.roleId == this.roleIdEnum.MERCHANT || this.userInfo.roleId == this.roleIdEnum.SUB_ACCOUNT){
      this.findMerchantTurnoverTop();
      this.findMerchantOrderCountTop();
    }
    setTimeout(() => {
      if (this.curIndex == 0) {
        this.selectSales();
        console.log('curIndex：' + this.curIndex);
      }
      if (this.curIndex == 1) {
        console.log('走进订单日表生成');
        this.selectCount();
        console.log('curIndex：' + this.curIndex);
      }
      if (this.curIndex == 2) {
        this.selectProfit();
        console.log('curIndex：' + this.curIndex);
      }
    }, 100);
  }

  //每月销售额统计
  monthSalesChart(chartWidth) {
    const data = [
      {year: '1 月', 销售额: 0.00, dateStr: '01'},
      {year: '2 月', 销售额: 0.00, dateStr: '02'},
      {year: '3 月', 销售额: 0.00, dateStr: '03'},
      {year: '4 月', 销售额: 0.00, dateStr: '04'},
      {year: '5 月', 销售额: 0.00, dateStr: '05'},
      {year: '6 月', 销售额: 0.00, dateStr: '06'},
      {year: '7 月', 销售额: 0.00, dateStr: '07'},
      {year: '8 月', 销售额: 0.00, dateStr: '08'},
      {year: '9 月', 销售额: 0.00, dateStr: '09'},
      {year: '10 月', 销售额: 0.00, dateStr: '10'},
      {year: '11 月', 销售额: 0.00, dateStr: '11'},
      {year: '12 月', 销售额: 0.00, dateStr: '12'},
    ];
    let type = 2;
    this.baseService.get(ApiUrl.HomeUrl + '/findMonthlyTurnover?type=' + type).subscribe(res => {
      console.log("数据：",res.data);
      //循环将查询到的数据修改到data数组里面
      res.data.forEach(i => {
        data.forEach((item, index) => {
          if (item.dateStr == i.dateStr) {
            //修改
            item.销售额 = i.turnover;
          }
        });
      });
      const chart = new Chart({
        container: 'monthSales',
        autoFit: true,
        height: 400,
        width: chartWidth,
        padding: [30, 20, 60, 60],
      });

      chart.data(data);
      chart.scale('销售额', {
        nice: true,
      });

      chart.tooltip({
        showMarkers: false
      });
      chart.interaction('active-region');

      chart.interval().position('year*销售额')
        .color('#58afff');

      chart.render();
    });
  }

  //统计每月的订单数
  monthCountChart(chartWidth) {
    const data = [
      {year: '1 月', 订单数: 0.00, dateStr: '01'},
      {year: '2 月', 订单数: 0.00, dateStr: '02'},
      {year: '3 月', 订单数: 0.00, dateStr: '03'},
      {year: '4 月', 订单数: 0.00, dateStr: '04'},
      {year: '5 月', 订单数: 0.00, dateStr: '05'},
      {year: '6 月', 订单数: 0.00, dateStr: '06'},
      {year: '7 月', 订单数: 0.00, dateStr: '07'},
      {year: '8 月', 订单数: 0.00, dateStr: '08'},
      {year: '9 月', 订单数: 0.00, dateStr: '09'},
      {year: '10 月', 订单数: 0.00, dateStr: '10'},
      {year: '11 月', 订单数: 0.00, dateStr: '11'},
      {year: '12 月', 订单数: 0.00, dateStr: '12'},
    ];
    let type = 2;
    this.baseService.get(ApiUrl.HomeUrl + '/findMonthlyOrderCount?type=' + type).subscribe(res => {
      //循环将查询到的数据修改到data数组里面
      res.data.forEach(i => {
        data.forEach((item, index) => {
          if (item.dateStr == i.dateStr) {
            item.订单数 = i.orderCount;
          }
        });
      });
      const chart = new Chart({
        container: 'monthCount',
        autoFit: true,
        height: 400,
        width: chartWidth,
        padding: [30, 20, 60, 60],
      });

      chart.data(data);
      chart.scale('订单数', {
        nice: true,
      });

      chart.tooltip({
        showMarkers: false
      });
      chart.interaction('active-region');

      chart.interval().position('year*订单数')
        .color('#58afff');

      chart.render();
    });
  }

  //统计每月的利润
  monthProfitChart(chartWidth) {
    const data = [
      {year: '1 月', 利润: 0.00, dateStr: '01'},
      {year: '2 月', 利润: 0.00, dateStr: '02'},
      {year: '3 月', 利润: 0.00, dateStr: '03'},
      {year: '4 月', 利润: 0.00, dateStr: '04'},
      {year: '5 月', 利润: 0.00, dateStr: '05'},
      {year: '6 月', 利润: 0.00, dateStr: '06'},
      {year: '7 月', 利润: 0.00, dateStr: '07'},
      {year: '8 月', 利润: 0.00, dateStr: '08'},
      {year: '9 月', 利润: 0.00, dateStr: '09'},
      {year: '10 月', 利润: 0.00, dateStr: '10'},
      {year: '11 月', 利润: 0.00, dateStr: '11'},
      {year: '12 月', 利润: 0.00, dateStr: '12'},
    ];
    let type = 2;
    this.baseService.get(ApiUrl.HomeUrl + '/findMonthlyTotalCommission?type=' + type).subscribe(res => {
      //循环将查询到的数据修改到data数组里面
      res.data.forEach(i => {
        data.forEach((item, index) => {
          if (item.dateStr == i.dateStr) {
            item.利润 = i.totalCommission;
          }
        });
      });
      const chart = new Chart({
        container: 'monthProfit',
        autoFit: true,
        height: 400,
        width: chartWidth,
        padding: [30, 20, 60, 60],
      });

      chart.data(data);
      chart.scale('利润', {
        nice: true,
      });

      chart.tooltip({
        showMarkers: false
      });
      chart.interaction('active-region');

      chart.interval().position('year*利润')
        .color('#58afff');

      chart.render();
    });
  }

  /**
   * 按日查看销售量
   */
  daySalesChart(chartWidth,) {

    const salesData = [];
    // 获取当前天数
    let day = new Date().getDate();
    // 不查一号
    if (day > 1) {
      //本月过去几天就循环几天,不查当天所以减1
      for (let i = 1; i <= day - 1; i++) {
        let item = {'day': i + '号', 'month': '本月', 'sales': 0.00, dateStr: i};
        salesData.push(item);
      }
    }
    this.baseService.get(ApiUrl.HomeUrl + '/findMonthlyTurnover?type=' + 1).subscribe(res => {
      console.log("数据1：",res.data);
      res.data.forEach(i => {
        salesData.forEach((item) => {
          if (item.dateStr == i.dateStr) {
            item.sales = i.turnover;
          }
        });
      });

      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth();
      let d = new Date(year, month, 0);

      for (let i = 1; i <= d.getDate(); i++) {
        let item = {'day': i + '号', 'month': '上月', 'sales': 0.00, dateStr: i};
        salesData.push(item);
      }
      this.baseService.get(ApiUrl.HomeUrl + '/findMonthlyTurnover?type=' + -1).subscribe(res2 => {
        res2.data.forEach(i => {
          salesData.forEach((item) => {
            //上个月的数据需要判断一下
            if (item.month == '上月') {
              //判断是否和查询出来的数据相等
              if (item.dateStr == i.dateStr) {
                item.sales = i.turnover;
              }
            }
          });
        });
        const salesChart = new Chart({
          container: 'daySales',
          autoFit: true,
          height: 400,
          width: chartWidth,
          padding: [20, 20, 80, 80], // 上，右，下，左
        });

        salesChart.data(salesData);
        salesChart.scale({
          day: {
            range: [0, 1],
          },
          sales: {
            nice: true,
          },
        });

        salesChart.tooltip({
          showCrosshairs: true,
          shared: true,
        });

        salesChart.axis('sales', {
          label: {
            formatter: (val) => {
              return val + ' 元';
            },
          },
        });

        //辅助线为虚线不起作用
        salesChart.annotation().line({
          start: [100, 'min'],
          end: [2000, 'max'],
          style: {
            lineDash: [10, 10]
          }
        });

        salesChart
          .line()
          .position('day*sales')
          .color('month')
          .shape('smooth');

        salesChart
          .point()
          .position('day*sales')
          .color('month')
          .shape('circle');
        salesChart.render();

      });
    });

  }


  /**
   * 按日查看订单笔数
   */
  dayCountChart(chartWidth,) {
    const countData = [];
    // 获取当前天数
    let day = new Date().getDate();
    // 不查一号
    if (day > 1) {
      //本月过去几天就循环几天,不查当天的,减一
      for (let i = 1; i <= day - 1; i++) {
        let item = {'day': i + '号', 'month': '本月', 'count': 0.00, dateStr: i};
        countData.push(item);
      }
    }
    this.baseService.get(ApiUrl.HomeUrl + '/findMonthlyOrderCount?type=' + 1).subscribe(res => {
      console.log("数据2：",res.data);
      //双重循环,把已有的数据修改到数组里面
      res.data.forEach(i => {
        countData.forEach((item) => {
          if (item.dateStr == i.dateStr) {
            item.count = i.orderCount;
          }
        });
      });
      for (let i = 1; i <= 31; i++) {
        let item = {'day': i + '号', 'month': '上月', 'count': 0.00, dateStr: i};
        countData.push(item);
      }
      this.baseService.get(ApiUrl.HomeUrl + '/findMonthlyOrderCount?type=' + -1).subscribe(res2 => {
        res2.data.forEach(i => {
          countData.forEach((item) => {
            //这是查上个月的数据
            if (item.month == '上月') {
              //判断是否和查询出来的数据相等
              if (item.dateStr == i.dateStr) {
                //赋值
                item.count = i.orderCount;
              }
            }
          });
        });
        const chart = new Chart({
          container: 'dayCount',
          autoFit: true,
          height: 400,
          width: chartWidth,
          padding: [20, 20, 80, 80], // 上，右，下，左
        });
        chart.data(countData);
        chart.scale({
          day: {
            range: [0, 1],
          },
          sales: {
            nice: true,
          },
        });

        chart.tooltip({
          showCrosshairs: true,
          shared: true,
        });

        chart.axis('count', {
          label: {
            formatter: (val) => {
              return val + ' 笔';
            },
          },
        });

        //辅助线为虚线不起作用
        chart.annotation().line({
          start: [100, 'min'],
          end: [2000, 'max'],
          style: {
            lineDash: [10, 10]
          }
        });

        chart
          .line()
          .position('day*count')
          .color('month')
          .shape('smooth');

        chart
          .point()
          .position('day*count')
          .color('month')
          .shape('circle');

        chart.render();
      });
    });
  }

  /**
   * 按日查看利润
   */
  dayProfitChart(chartWidth,) {
    const prpfotData = [];
    // 获取当前天数
    let day = new Date().getDate();
    //一号不需要要查
    if (day > 1) {
      //本月过去几天就循环几天,不循环今天的,所以减1
      console.log(day);
      for (let i = 1; i <= day - 1; i++) {
        let item = {'day': i + '号', 'month': '本月', 'profit': 0.00, dateStr: i};
        prpfotData.push(item);
      }
    }
    this.baseService.get(ApiUrl.HomeUrl + '/findMonthlyTotalCommission?type=' + 1).subscribe(res => {
      //双重循环,把已有的数据修改到数组里面
      res.data.forEach(i => {
        prpfotData.forEach((item) => {
          if (item.dateStr == i.dateStr) {
            item.profit = i.totalCommission;
          }
        });
      });
      for (let i = 1; i <= 31; i++) {
        let item = {'day': i + '号', 'month': '上月', 'profit': 0.00, dateStr: i};
        prpfotData.push(item);
      }
      this.baseService.get(ApiUrl.HomeUrl + '/findMonthlyTotalCommission?type=' + -1).subscribe(res2 => {
        res2.data.forEach(i => {
          prpfotData.forEach((item) => {
            //这是查上个月的数据
            if (item.month == '上月') {
              //判断是否和查询出来的数据相等
              if (item.dateStr == i.dateStr) {
                //赋值
                item.profit = i.totalCommission;
              }
            }
          });
        });
        const chart = new Chart({
          container: 'dayProfit',
          autoFit: true,
          height: 400,
          width: chartWidth,
          padding: [20, 20, 80, 80], // 上，右，下，左
        });
        chart.data(prpfotData);
        chart.scale({
          day: {
            range: [0, 1],
          },
          sales: {
            nice: true,
          },
        });

        chart.tooltip({
          showCrosshairs: true,
          shared: true,
        });

        chart.axis('profit', {
          label: {
            formatter: (val) => {
              return val + ' 元';
            },
          },
        });

        //辅助线为虚线不起作用
        chart.annotation().line({
          start: [100, 'min'],
          end: [2000, 'max'],
          style: {
            lineDash: [10, 10]
          }
        });

        chart
          .line()
          .position('day*profit')
          .color('month')
          .shape('smooth');

        chart
          .point()
          .position('day*profit')
          .color('month')
          .shape('circle');

        chart.render();
      });
    });
  }
}
